package org.darkforest.merchant.controller;

import com.alibaba.fastjson.JSON;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.Page;
import org.darkforest.controller.WebController;
import org.darkforest.dao.mapper.AlbumClassMapper;
import org.darkforest.dao.mapper.AlbumPicMapper;
import org.darkforest.enums.AjaxAlbumTypeEnum;
import org.darkforest.enums.AjaxMsgTypeEnum;
import org.darkforest.merchant.factory.AlbumAjaxCodeFactory;
import org.darkforest.common.services.IAlbumClassService;
import org.darkforest.model.AlbumClass;
import org.darkforest.model.AlbumPic;
import org.darkforest.model.AlbumPicPageBean;
import org.darkforest.model.Store;
import org.darkforest.ucenter.auth.AuthPassport;
import org.darkforest.vo.AjaxReturnData;
import org.darkforest.vo.StoreSellerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by chenyu on 15/1/29.
 * 商品图片相册控制类
 */
@RequestMapping(value = "/album")
@Controller
public class AlbumController extends WebController<AlbumController> {
    @Autowired
    private AlbumClassMapper albumDao;
    @Autowired
    private IAlbumClassService albumClassService;
    @Autowired
    private AlbumPicMapper picDao;

    @Value("#{configProperties['pic.compressSize']}")
    private String compressPicSize;                     //图片压缩尺寸从配置文件中读取
    @Value("#{configProperties['pic.tempPath']}")
    private String picTempPath;                         //图片上传临时目录,避免写死尽量配置为变量
    @Autowired
    private AlbumAjaxCodeFactory albumAjaxCodeFactory;
//    @Value("#{configProperties['alioss.path']}")
//    private String alioss_path;                         //图片访问路径前缀

    /**
     * 相册列表页
     *
     * @return
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String album_list(HttpServletRequest request) {
        Integer storeId = ((StoreSellerVo) request.getSession().getAttribute("sellerInfo")).getStoreId();
        List<AlbumClass> album = albumDao.getAlbumbyStoreId(storeId);
        if (storeId != null) {
            request.setAttribute("albumList", album);
        }
       // LOGGER.debug("album size:" + album.size() + ",id:" + album.get(0).getAclassName());
        return "album/list";
    }

    /**
     * 相册列表页
     * @return
     */
    @RequestMapping(value = "listSort")
    public String album_sort(HttpServletRequest request,AlbumClass albumClass) {
        Integer storeId = ((StoreSellerVo) request.getSession().getAttribute("sellerInfo")).getStoreId();
        albumClass.setStoreId(storeId);
        if(albumClass.getSort()!=null){
            if(albumClass.getSort().equals("0")){
                albumClass.setOrderByColum("upload_time");
                albumClass.setOrderByType("asc");
            }else if(albumClass.getSort().equals("1")){
                albumClass.setOrderByColum("upload_time");
                albumClass.setOrderByType("desc");
            }else if(albumClass.getSort().equals("2")){
                albumClass.setOrderByColum("aclass_name");
                albumClass.setOrderByType("desc");
            }else if(albumClass.getSort().equals("3")){
                albumClass.setOrderByColum("aclass_name");
                albumClass.setOrderByType("asc");
            }else if(albumClass.getSort().equals("4")){
                albumClass.setOrderByColum("aclass_sort");
                albumClass.setOrderByType("desc");
            }else if(albumClass.getSort().equals("5")){
                albumClass.setOrderByColum("aclass_sort");
                albumClass.setOrderByType("asc");
            }
        }
        albumClass.setPageSwitch(false);
        List<AlbumClass> list = albumDao.selectByCondition(albumClass);
        if (storeId != null) {
            request.setAttribute("albumList", list);
            request.setAttribute("album", albumClass);
        }
        return "album/list";
    }


    /**
     * 图片ajax上传方法toJSONString
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "imageUpload", method = RequestMethod.POST)
    public @ResponseBody String imageUpload(MultipartHttpServletRequest request) {
        LinkedList<AlbumPic> files = new LinkedList<AlbumPic>();
        AlbumPic pic = null;
        StoreSellerVo store = (StoreSellerVo) request.getSession().getAttribute("sellerInfo");
        Integer storeId = store.getStoreId();
        Integer albumId = request.getParameter("category_id") == null ? store.getDefaultAlbumId() : Integer.parseInt(request.getParameter("category_id"));
        String tempPath = request.getSession().getServletContext().getRealPath(picTempPath) + "/";
        LOGGER.debug("=======tempPath:" + tempPath + ",albumId:" + albumId);
        files = this.uploadPics(request, null, null, albumId.toString());
        LOGGER.debug("共上传：" + files.size() + "个文件");
        for (AlbumPic albumPic : files) {
            //存储数据到数据库
            albumPic.setAclassId(albumId);
            albumPic.setStoreId(storeId);
            picDao.insert(albumPic);
        }
        return JSON.toJSONString(files);
    }


    /**
     * 图片ajax上传方法
     *
     * @param request
     * @return
     */
    @AuthPassport
    @RequestMapping(value = "image_upload", method = RequestMethod.POST)
    public
    @ResponseBody
    LinkedList<AlbumPic> image_upload(MultipartHttpServletRequest request) {
        LinkedList<AlbumPic> files = new LinkedList<AlbumPic>();
        StoreSellerVo store = (StoreSellerVo) request.getSession().getAttribute("sellerInfo");
        Integer storeId = store.getStoreId();
        Integer albumId = request.getParameter("category_id") == null ? store.getDefaultAlbumId() : Integer.parseInt(request.getParameter("category_id"));
        String tempPath = request.getSession().getServletContext().getRealPath(picTempPath) + "/";
        LOGGER.debug("=======tempPath:" + tempPath + ",albumId:" + albumId);
        files = this.uploadPics(request, null, null, albumId.toString());
        LOGGER.debug("共上传：" + files.size() + "个文件");
        for (AlbumPic albumPic : files) {
            //存储数据到数据库
            albumPic.setAclassId(albumId);
            albumPic.setStoreId(storeId);
            picDao.insert(albumPic);
        }
        return files;
    }


    /**
     * 新增
     *
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView albumAdd() {
        ModelAndView modelAndView = new ModelAndView("album/album_edit", "album", new AlbumClass());
        modelAndView.addObject("title","创建相册");
        return modelAndView;
    }

    /**
     * 编辑
     * @param id
     * @return
     */
    @RequestMapping(value = "edit/{id}",method = RequestMethod.GET)
    public ModelAndView albumEdit(@PathVariable int id){
        ModelAndView modelAndView = new ModelAndView("album/album_edit","album",albumDao.selectByPrimaryKey(id));
        modelAndView.addObject("title","编辑相册");
        return modelAndView;
    }

    /**
     * 删除，只删除相册数据，不删除图片数据，相册图片更新到其他相册
     * @param albumId
     * @return
     */
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public @ResponseBody AjaxReturnData albumDel(Integer albumId){
        AjaxReturnData data = new AjaxReturnData();
        data.setUrl("album/list");
        data.setMessage("相册删除成功");
        data.setType(AjaxMsgTypeEnum.SUCC.getText());
        if(albumId!=null){
            albumDao.updateDelAlbumPic(albumId);
            albumDao.deleteByPrimaryKey(albumId);
        }else {
            data.setMessage("相册删除异常");
            data.setType(AjaxMsgTypeEnum.INFO.getText());
        }
        return  data;
    }

    @RequestMapping(value = "check_album_name",method = RequestMethod.POST)
    public @ResponseBody String check_album_name(@RequestParam String ac_name,Integer ac_id){
        LOGGER.debug("ac_name:"+ac_name+",ac_id:"+ac_id);
        AlbumClass albumClass = new AlbumClass();
        albumClass.setAclassId(ac_id);
        albumClass.setAclassName(ac_name);
        if(ac_id !=null){
            AlbumClass ac = new AlbumClass();
            ac.setAclassName(ac_name);
            if(albumDao.getAlbumClassCntByName(albumClass) ==0 && albumDao.getAlbumClassCntByName(ac)>0 ){
                return "<i class='icon-exclamation-sign'></i>相册名称已存在";
            }
            return "true";
        }else{
            if(albumDao.getAlbumClassCntByName(albumClass)>0){
                return "<i class='icon-exclamation-sign'></i>相册名称已存在";
            }
            return "true";
        }

    }

    @RequestMapping("msg")
    public String showMsg(){
        return "msg";
    }

    @AuthPassport
    @RequestMapping(value="album_save")
    public String album_save(AlbumClass album,HttpServletRequest request){
        Integer res=0;
        String resMsg = "";
        LOGGER.debug("aclassName:"+album.getAclassName()+","+album.getAclassDes()+","+album.getStoreId());
        StoreSellerVo store = (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        //新增
        if(album.getAclassId()==null){
            album.setUploadTime(DateUtil.unixTimeStamp());
            album.setAclassSort(album.getAclassSort()==null?(byte)99:album.getAclassSort());
            List<AlbumClass> albumClasses  = albumDao.selectByCondition(new AlbumClass(store.getStoreId(),1));
//            album.setIsDefault(albumClasses.size()>0?true:false);
            album.setIsDefault(albumClasses.size()>0 ? 0: 1);
            res = albumDao.insert(album);
            resMsg = "相册创建成功";
        }else{
            //更新
            album.setAclassSort(album.getAclassSort()==null?(byte)99:album.getAclassSort());
            res = albumDao.updateByPrimaryKeySelective(album);
            resMsg = "相册修改成功";
        }

        LOGGER.debug("res:"+res);
//        String msg = getDialogXMLTemplete(resMsg, AjaxMsgTypeEnum.SUCC,"list",2);
        String msg = getDialogJsTemplete(resMsg, AjaxMsgTypeEnum.SUCC,"list",2);
//        return new XmlBody(msg);
//        return "msg";
        return "redirect:picList?aclass="+album.getAclassId();


    }


    /**
     * 图片分页列表
     *
     * @return
     */
    @RequestMapping(value = "picList", method = RequestMethod.GET)
    public String pic_list(Integer page, Integer aclass, HttpServletRequest request) {
        Integer storeId = ((StoreSellerVo) request.getSession().getAttribute("sellerInfo")).getStoreId();
        AlbumPicPageBean pageBean = new AlbumPicPageBean(aclass, page == null ? 1 : page, Page.DEFAULT_PAGE_SIZE);
        pageBean.setStoreId(storeId);
        List<AlbumPic> albumPics = picDao.getAlbumPicList(pageBean);
        pageBean.setResultList(albumPics);
//        pageBean.setCount(albumPics.size());
        request.setAttribute("picPageBean", pageBean);
//        request.setAttribute("pageCount",albumPics.size() / pageBean.getPageSize()+ (albumPics.size() % pageBean.getPageSize() > 0 ? 1 : 0));
        request.setAttribute("album",albumDao.selectByPrimaryKey(aclass));
        return "album/pic_list";
    }

    /**
     * 商品发布页面中ajax读取图片列表
     *
     * @param page
     * @param albumId
     * @param request
     * @return
     */
    @RequestMapping("ajaxPicList")
    public
    @ResponseBody
    String ajax_pic_list(Integer page, Integer albumId,  Integer specSize,String insertType, HttpServletRequest request, HttpServletResponse response) {
        Integer storeId = ((StoreSellerVo) request.getSession().getAttribute("sellerInfo")).getStoreId();
        List<AlbumClass> albumList = albumClassService.getAlbumClassList(storeId);
        page = page == null ? 1 : page;
        AlbumPicPageBean pageBean = new AlbumPicPageBean(albumId, page, AjaxAlbumTypeEnum.GALLERY.getText().equals(insertType) ? Page.PIC_AJAX_GALLERY_SIZE : Page.PIC_AJAX_PAGE_SIZE);
        pageBean.setStoreId(storeId);
        pageBean.setResultList(picDao.getAlbumPicList(pageBean));

//        String aliyun_path = (String)request.getSession().getServletContext().getAttribute("alioss_path");
        String base_path = (String) request.getSession().getServletContext().getAttribute("basePath");
//        return getAjaxPicList(albumList,pageBean,insertType,base_path,aliyun_path);
        return AlbumAjaxCodeFactory.getAlbumAjaxCode(base_path, albumList, pageBean, AjaxAlbumTypeEnum.getAlbumType(insertType),specSize==null?0:specSize);
    }

    /**
     * 商品图片详情页,详情页相当于pageSize=9的图片分页,需将原图片位置转换为pageSize=9的分页信息
     *
     * @param albumId
     * @param page
     * @param idx
     * @param request
     * @return
     */
    @RequestMapping(value = "picDetail", method = RequestMethod.GET)
    public String pic_detail(Integer albumId, Integer page, Integer idx, HttpServletRequest request) {
        int pic_idx_defaultSize = (page - 1) * Page.DEFAULT_PAGE_SIZE + idx;                  //图片在分页列表的位置
        int pic_page_gallery = pic_idx_defaultSize / Page.PIC_GALLERY_PAGE_SIZE;             //重新计算图片在画廊的所在页数
        int pic_idx_gallery = pic_idx_defaultSize % Page.PIC_GALLERY_PAGE_SIZE;              //计算gallery页面的索引定位
        AlbumPicPageBean pageBean = new AlbumPicPageBean(albumId, pic_page_gallery, Page.PIC_GALLERY_PAGE_SIZE);
        pageBean.setResultList(picDao.getAlbumPicList(pageBean));
        request.setAttribute("picGallery", pageBean);
        request.setAttribute("picIdx", pic_idx_gallery);
        LOGGER.debug("gallery size:" + pageBean.getResultList().size() + ",page:" + pageBean.getStart() + "," +
                "idx:" + pic_idx_gallery);
        request.setAttribute("album",albumDao.selectByPrimaryKey(albumId));
        return "album/pic_gallery";
    }

    /**
     * 图片删除：数据库数据删除，云端图片删除
     * @param picId
     * @return
     */
    @RequestMapping(value = "picDel",method = RequestMethod.POST)
    public @ResponseBody AjaxReturnData pic_del(@RequestParam Integer albumId,@RequestParam String picId){
        LOGGER.debug("pics:"+picId+",");
        AjaxReturnData res = new AjaxReturnData();
        res.setUrl("album/picList?aclass="+albumId);
        String[] ids = picId.split(",");
        for(String i: ids){
            int s = picDao.deleteByPrimaryKey(Integer.parseInt(i));
            if(s>0){
                // TODO 删除云端图片
                res.setMessage("图片删除成功");
                res.setType(AjaxMsgTypeEnum.SUCC.getText());
            }else{
                res.setType(AjaxMsgTypeEnum.INFO.getText());
                res.setMessage("图片删除失败");
            }
        }

        return res;
    }

    /**
     * 设置相册封面
     * @return
     */
    @RequestMapping(value = "setCover",method = RequestMethod.POST)
    public @ResponseBody AjaxReturnData setConver(@RequestParam Integer albumId,@RequestParam String picId){
        AjaxReturnData res = new AjaxReturnData();
        res.setUrl("album/picList?aclass="+albumId);
        int s = albumDao.updateCover(new AlbumClass(albumId,picId));
        if(s>0){
            res.setMessage("操作成功");
            res.setType(AjaxMsgTypeEnum.SUCC.getText());
        }else{
            res.setType(AjaxMsgTypeEnum.INFO.getText());
            res.setMessage("操作失败");
        }
        return res;
    }
}
